import requests
import base64
from mdpro.settings import BASE_DIR

url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=tjYz2u2VPSGUZTteGAKANeN6&client_secret=j94Ct3M1pOK0h3xXPnTq3P7DWAzuyobL'


def acquire_access_token():
    response = requests.get(url=url)
    access_token = response.json().get('access_token')
    return access_token


def recognition_word():
    # 二进制方式打开图片文件
    f = open('{}\\myutils\\123.png'.format(BASE_DIR), 'rb')
    img = base64.b64encode(f.read())
    data = {"image": img}
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    access_token = acquire_access_token()
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + access_token
    # 使用requests发送post请求 里面需要以下参数： url，请求地址， data 所需要请求的参数， headers代表请求头
    response = requests.post(request_url, data=data, headers=headers)
    if response:
        print(response.json().get('words_result'))


if __name__ == '__main__':
    # print(acquire_access_token())
    recognition_word()